package com.fwtai.service.api;

import com.fwtai.api.ApiProductShowDao;
import com.fwtai.bean.PageFormData;
import com.fwtai.service.AsyncService;
import com.fwtai.tool.ToolClient;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;

/**
 * 产品展示业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @Email service@fwtai.com
 * @创建日期 2024-02-06 19:31:40
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class ApiProductShowService{

  private final AsyncService asyncService;

  private final ApiProductShowDao apiProductShowDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public ApiProductShowService(final ApiProductShowDao apiProductShowDao,final ThreadPoolTaskExecutor taskExecutor,final AsyncService asyncService){
    this.apiProductShowDao = apiProductShowDao;
    this.taskExecutor = taskExecutor;
    this.asyncService = asyncService;
  }

  public String queryById(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      final HashMap<String,Object> map = apiProductShowDao.queryById(kid);
      if(!map.isEmpty()){
        asyncService.updateProductPv(kid,taskExecutor);
      }
      return ToolClient.queryJson(map);
    },taskExecutor).join();
  }

  /**适用于api接口,仅含数据不含总记录数总条数,前端仅做返回的数据是否小于每页大小*/
  public String listData(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = ToolClient.pageParamsApi(request);
      if(formData == null) return ToolClient.jsonValidateField();
      return ToolClient.jsonPage(apiProductShowDao.getListData(formData));
    },taskExecutor).join();
  }
}